package com.gemme.gemme.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.MainActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.login.BindInputTelActivity;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.login.MsgActivity;
import com.gemme.gemme.login.PersonInfoActivity;
import com.gemme.gemme.login.UseInfoBean;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.util.DpUtil;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.util.ShapeUtil;
import com.hyphenate.chat.ChatClient;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yangcheng
 * @CreateDate: 2020/7/24 15:07
 */

/*
* 微信登录
* 1,获取微信授权
* 2,判断是否有账号,有直接登陆
* 3,无走手机号,
* 4,微信号绑定
* 5,验证码登录注册
* */
public class SanfangLoginUtil {
    public static  String weixin_accessToken;
    public static  String weixin_openid;
    public static String account;
    public static   String msg;
    public static EditText et_acount;
    public static EditText et_msg;
    public static void createWeinDialog(Context mContext){
        getWeiXinOpenId(mContext);
    }

    private static void toDialogShow(Context context){
        BottomDialog dialog = new BottomDialog(context, R.layout.weixin_dialog,
                new int[]{R.id.tv_close,R.id.tv_code,R.id.bt_confirm});


        dialog.show();
        et_acount = dialog.findViewById(R.id.et_acount);
        et_msg = dialog.findViewById(R.id.et_msg);
        dialog.setOnBottomItemClickListener(new BottomDialog.OnBottomItemClickListener() {
            @Override
            public void onBottomItemClick(BottomDialog dialog, View view) {
                switch (view.getId()) {
                    case R.id.tv_close:
                        dialog.dismiss();
                        break;

                    case R.id.tv_code:

                        account = et_acount.getText() + "";
                        if(TextUtils.isEmpty(account)){
                            Toast.makeText(context, "手机号不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        toWeiXinMsg(context);
                        break;

                    case R.id.bt_confirm:
                        account =et_acount.getText() + "" + "";
                        msg = et_msg.getText() + "" + "";

                        if(TextUtils.isEmpty(account) || TextUtils.isEmpty(msg) ){

                            Toast.makeText(context, "手机号和验证码不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        }

//                        toWeixinLogin(context);
                        weixinSign(context);
                        break;

                }
            }
        });
    }


    public static void getWeiXinOpenId(Context context){
        //获取微信授权
        UMShareAPI.get(context).getPlatformInfo((Activity)context, SHARE_MEDIA.WEIXIN, new UMAuthListener(){

            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                System.out.println("");
                System.out.println("");
//                        et_accessToken.setText();
                 weixin_accessToken = map.get("accessToken") + "";
                 weixin_openid = map.get("openid") + "";
                System.out.println("");


                isbindingmobile(context);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                System.out.println("");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }


    //检测微信号是否存在
    private static void isbindingmobile(Context context) {
        if(TextUtils.isEmpty(weixin_openid))
            return;
        //http://192.168.1.6:9999/user/userapp/isbindingmobile?openId=35_-NVQprUOyqmdeyoGa8CR-uE4TEneDd5rCYwt6vSvbtjc5Dp5ZjlFvHIlvjiYD1ToE4qbKy18Fdyo4t5CWrx_g5X-K2tOrG7RPPG1S6T2ulQ
        String url = DataManager.BaseUrl + "user/userapp/isbindingmobile?" +
                "openId=" + weixin_openid;
        ;
        HashMap<String, String> headMap = new HashMap<>();
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject = new JSONObject(response);
                    boolean isbindingmobile = jsonObject.getBoolean("data");
                    System.out.println("");

                    if(isbindingmobile){//已绑定获取用户信息
                        toWeixinLogin(context);
                    }else{//未绑定去验证码注册
                       /* Intent intent = new Intent(context, BindInputTelActivity.class);
                        intent.putExtra("weixin_openid",weixin_openid);
                        intent.putExtra("weixin_accessToken",weixin_accessToken);
                        intent.putExtra(MsgActivity.TYPE,MsgActivity.type_weixin);
                        context.startActivity(intent);*/
                        toDialogShow(context);

                    }
                }catch (Exception e){

                }
            }
        });
    }



    private static void toWeiXinMsg(Context context) {
        if(TextUtils.isEmpty(account)){
            Toast.makeText(context, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String url = DataManager.BaseUrl + "user/userapp/bindingsms?" +
                "smsType=" + "binding_wx"
                +"&mobile=" + account
                ;
        HashMap<String, String> headMap = new HashMap<>();
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject = new JSONObject(response);
                    boolean bindingsms = jsonObject.getBoolean("data");
                    msg = jsonObject.getString("msg");
                    System.out.println("");

                    if(TextUtils.isEmpty(msg)){
                        Toast.makeText(context, "验证码获取失败", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context, "获取验证码成功", Toast.LENGTH_SHORT).show();
                    }

                    if(bindingsms ){//获取验证码成功
                        System.out.println("");
//                        weixinSign(msg);
                    }else{
                    }
                }catch (Exception e){

                }
            }
        });
    }


    //微信号绑定
    private static void weixinSign(Context context) {
        if(TextUtils.isEmpty(account)){
            Toast.makeText(context, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(msg)){
            Toast.makeText(context, "验证码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = DataManager.BaseUrl + "user/userapp/bindingmobile?" +
                "mobile=" + account
                +"&smsCode=" + et_msg.getText().toString()
                ;
        ;
        HashMap<String, String> headMap = new HashMap<>();
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject = new JSONObject(response);
                    boolean bindingmobile = jsonObject.getBoolean("data");
                    System.out.println("");

                    if(bindingmobile){//绑定成功
                        Toast.makeText(context, "" + jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                        toWeixinLogin(context);
                    }{
                        Toast.makeText(context, "" + jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                    }


                }catch (Exception e){

                }
            }
        });
    }


    private static void toWeixinLogin(Context context) {


        if(TextUtils.isEmpty(weixin_openid) || TextUtils.isEmpty(weixin_accessToken)){
            Toast.makeText(context, "缺少数据", Toast.LENGTH_SHORT).show();
            return;
        }



        String url = DataManager.BaseUrl + "auth/mobile/token/social?" +
                "phone=WX@" + weixin_openid
                +"&grant_type=" + "mobile"
                +"&access_token=" + "" + weixin_accessToken
                +"&telephone=" + "" + (et_acount == null ? "" : et_acount.getText() + "")
                ;

        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("Authorization","Basic bW9iaWxlOm1vYmlsZQ==");
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    UseInfoBean useInfos = JSON.parseObject(response,UseInfoBean.class);
                    SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
                /*   Constant.ACCESS_TOKEN = useInfos.getAccess_token();+
                   Constant.REFRESH_TOKEN = useInfos.getRefresh_token();
                   Constant.ACCESS_TOKENTIME = System.currentTimeMillis();
                   Constant.REFRESH_TIME = System.currentTimeMillis();*/
                    MSP.edit().putString(Constant.ACCESS_TOKEN, useInfos.getAccess_token()).apply();
                    MSP.edit().putString(Constant.REFRESH_TOKEN, useInfos.getRefresh_token()).apply();
                    MSP.edit().putString(Constant.UserId, useInfos.getUser_info().getId() + "").apply();
                    MSP.edit().putString(Constant.ACCESS_TOKENTIME, System.currentTimeMillis() + "").apply();
                    MSP.edit().putString(Constant.REFRESH_TIME, System.currentTimeMillis() + "").apply();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            DataManager.refreshToken(context);

                            Handler mainHandler = new Handler(Looper.getMainLooper());
                            mainHandler.post(() -> {
//                                doSomething();
                                //登陆成功,首次进入个人信息页
                                ChatClient.getInstance().isLoggedInBefore();
                                Log.e("#######","Login"+ ChatClient.getInstance().isLoggedInBefore());
                                String dataForString = SPUtil.getDataForString(context, Constant.isFirstLogin, "0");
                                if("0".equals(dataForString)){
                                    context.startActivity(new Intent(context, PersonInfoActivity.class));
                                    //去除是首次登录
                                    SPUtil.PutData(context, Constant.isFirstLogin, "-1");
                                }else{
                                    context.startActivity(new Intent(context,MainActivity.class));

//                        context.startActivity(new Intent(context,MainActivity.class));
                                }

//                    context.startActivity(new Intent(context, MainActivity.class));
                                if(context instanceof Activity){
                                    ((Activity)context).finish();
                                }
                            });



                        }
                    }).start();



                }catch (Exception e){

                }
            }
        });
    }
}
